<?php


namespace App\Models;


use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    protected $dateFormat = 'U';

    protected $hidden = ['deleted_at'];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    //省份关联
    public function province()
    {
        return $this->hasOne(ImProvince::class, 'province_id', 'province_id');
    }

    //城市关联
    public function city()
    {
        return $this->hasOne(ImCity::class, 'city_id', 'city_id');
    }

    //区域关联
    public function area()
    {
        return $this->hasOne(ImArea::class, 'area_id', 'area_id');
    }

    //地址处理
    public static function addressPress($data)
    {
        foreach ($data as &$val) {
            $address = '';
            if (isset($val['province'])) {
                $address .= $val['province']->province;
            }
            if (isset($val['city'])) {
                $address .= $val['city']->city;
            }
            if (isset($val['area'])) {
                $address .= $val['area']->area;
            }
            if (isset($val['address'])) {
                $address .= $val['address'];
            }
            $val['addr'] = $address;
            unset($val['province']);
            unset($val['city']);
            unset($val['area']);
            unset($val['address']);
        }
        return $data;
    }

    /**
     * @param int $page 页码
     * @param int $pageNum 数据条数,不传默认 15
     * @return array [分页起始位置,数据条数]
     */
    public static function pageProcess($page = null, $pageNum = null)
    {
        if (!$page) {
            $page = request('page', 1);
        }
        if (!$pageNum) {
            $pageNum = request('pageNum', 15);
        }
        if ($page <= 0) {
            $page = 1;
        }
        if ($pageNum < 1) {
            $pageNum = 15;
        }
        $offset = ($page - 1) * $pageNum;
        return [$offset, $pageNum, $page, $pageNum];
    }
}
